<template>
	<view class="login">
		<view class="foot-action head-fixed child-view">
			<!-- 头部导航 -->
			<view class="w-750 title" style="position: fixed; top: 0; left: 0; z-index: 999;">
				<view class="h-100 w-row-justify-between-align">
					<view class="wh-80 w-row-center" @click="routerIndex()">
						<image class="wh-40" src="@/static/gane/goBack-icon.png"></image>
					</view>
					<view class="w-350 h-100 w-row-center w-wz-conts font-36">
						<text>登录</text>
					</view>
					<view class="wh-80 w-row-center">
					</view>
				</view>
			</view>
			<view class="bwh-120"></view>
			<!-- 头部导航结束 -->

			<view class="cover-tw index-bg absolute-default fixed">

			</view>

			<view class="content-box padding-top-xs" v-show="openPhone">
				<!-- <view class="padding padding-top-sm">
					<view class="text-lg text-bold text-color-black">
						欢迎来到六合国际娱乐
					</view>

				</view> -->
				<form class="van-form login">
					<view class="van-cell-group van-cell-group--inset">
						<view class="van-cell van-field van-field--label-top">
							<view class="van-cell__title van-field__label van-field__label--top">
								<label for="van-field-7-input">手机号</label>
							</view>

							<view class="van-cell__value van-field__value">
								<view class="van-field__body">
									<input type="text" id="van-field-7-input" v-model="formData.phone" name="username"
										class="van-field__control" placeholder="请填写手机号"
										aria-labelledby="van-field-7-label" :maxlength="11" @input="checkPhone">
									<view class="van-field__button">
										<button type="button" class="van-button van-button--warning van-button--small"
											:disabled="isPhone" id="captcha-button">
											<div class="van-button__content">
												<span class="van-button__text"
													v-if="count">重新获取{{count < 10 ? '0'+count :count}}秒</span>
												<span class="van-button__text" v-else>发送验证码</span>
											</div>
										</button>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="van-cell-group van-cell-group--inset">
						<view class="van-cell van-field van-field--label-top">
							<view class="van-cell__title van-field__label van-field__label--top">
								<label for="van-field-7-input">验证码</label>
							</view>

							<view class="van-cell__value van-field__value">
								<view class="van-field__body">
									<input type="text" id="van-field-7-input" v-model="formData.code" name="username"
										class="van-field__control" placeholder="请填写验证码"
										aria-labelledby="van-field-7-label" />
								</view>
							</view>
						</view>
					</view>
				</form>

				<view class="padding" v-if="openPhone">
					<button type="submit" class="van-button van-button--primary van-button--normal van-button--block"
						@click="phoneLogin" :disabled="login_loading">
						<div class="van-button__content"><span class="van-button__text">立即登录</span></div>
					</button>
					<!-- 添加微信登录按钮 -->

					<view class="margin-top-xs text-color-grey" style="float: right;">
						登录不上请联系，
						<span class="text-bold text-color-blue" @click="toIm()">在线客服</span>
					</view>
					<!-- <div class="margin-top-sm text-center text-color-grey">登录即注册，距离致富只差10秒</div> -->
				</view>

			</view>
			<view class="content-box padding-top-xs" style="margin-top:50rpx;" v-show="openLogin">
				<view class="text-lg text-bold text-color-black"
					style="padding:0 60rpx;display: flex;justify-content: space-between;align-items: center;">账密登录 <span
						@click="toRegister()" class="goRegister">去注册</span></view>
				<view class="text-lg  text-color-black"
					style="padding:20rpx 60rpx 10rpx 60rpx;font-size: 22rpx;margin-bottom:20px;">你也可以<span
						@click="toPhoneLogin()" class="goRegister" style="font-size:22rpx;">手机登录</span></view>
				<form class="van-form login">
					<view class="van-cell-group van-cell-group--inset">
						<view class="van-cell van-field van-field--label-top">
							<view class="van-cell__title van-field__label van-field__label--top">
								<label for="van-field-7-input">账号</label>
							</view>
							<view class="van-cell__value van-field__value">
								<view class="van-field__body">
									<input type="text" id="van-field-7-input" v-model="loginData.account"
										name="username" class="van-field__control" placeholder="请输入账号名"
										aria-labelledby="van-field-7-label">

								</view>
							</view>
						</view>
					</view>

					<view class="van-cell-group van-cell-group--inset">
						<view class="van-cell van-field van-field--label-top">
							<view class="van-cell__title van-field__label van-field__label--top">
								<label for="van-field-7-input">密码</label>
							</view>

							<view class="van-cell__value van-field__value">
								<view class="van-field__body">
									<input type="password" id="van-field-7-input" v-model="loginData.password"
										name="username" class="van-field__control" placeholder="请输入密码"
										aria-labelledby="van-field-7-label" />
								</view>
							</view>
						</view>
					</view>
				</form>

				<view class="padding">
					<button type="submit" class="van-button van-button--primary van-button--normal van-button--block"
						@click="accountLogin" :disabled="login_loading">
						<div class="van-button__content"><span class="van-button__text">立即登录</span></div>
					</button>
				</view>

			</view>

			<view class="margin-top-sm text-center text-color-grey padding" style="margin-top:200rpx"
				v-if="isWechatBrowser">
				<!-- 微信一键登录按钮 -->
				<button type="button"
					class=" btn-radius van-button van-button--warnings van-button--normal van-button--block margin-top-sm"
					@click="wechatLogin" v-if="this.config?.wx_login_open==1">
					<div class="van-button__content"><img src="/static/login/WeChat.png" /><span
							class="van-button__text" style="width: 250rpx;">微信一键登录</span></div>
				</button>

				<!-- 本机号码一键登录按钮 -->
				<button type="button"
					class="btn-radius van-button van-button--info van-button--normal van-button--block margin-top-sm"
					@click="oneKeyPhoneLogin">
					<div class="van-button__content"><img src="/static/login/phone.png" /><span class="van-button__text"
							style="margin-left:10rpx;">手机号码登录</span></div>
				</button>

				<!-- 本机号码一键登录按钮 -->
				<button type="button"
					class="btn-radius van-button van-button--info van-button--normal van-button--block margin-top-sm"
					@click="openLoginBox" v-if="this.config?.paw_login_open==1">
					<div class="van-button__content"><img src="/static/login/profile.png" /><span
							class="van-button__text" style="margin-left:10rpx;">账号密码登录</span></div>
				</button>

			</view>
		</view>
		<div id="captcha-element"></div>
	</view>
</template>

<script>
	import $H from '@/pages/common/request.js'
	export default {
		data() {
			return {
				openRegister: false,
				openLogin: false,
				isPhone: true,
				loginData: {
					account: null,
					password: null
				},
				registerData: {
					account: null,
					phone: null,
					code: null,
					password: null,
					password2: null
				},
				formData: {
					phone: null,
					code: null
				},
				wxData: {
					openid: null,
					nickname: null,
					headimgurl: null,
					agent_code: null
				},
				count: null,
				timer: null,
				agent_code: uni.getStorageSync('agent_code') || '',
				login_loading: false,
				captcha: null,
				captchaButton: null,
				isWechatBrowser: true,
				openPhone: false,
				config: null,
				isPhone2: true,
				is_login: 0,
			}
		},
		onLoad(e) {
			this.getConfig();
			if (e.openid) {
				this.wxData.openid = e.openid
				this.wxData.nickname = e.nickname
				this.wxData.headimgurl = e.headimgurl

				this.loginWithWechat();
			}
			if (e.is_login) {
				this.is_login = e.is_login
				this.isWechatBrowser = false
			}

		},
		mounted() {
			this.isWechatBrowser = this.checkIsWechatBrowser();
			this.captchaButton = document.getElementById('captcha-button');

			window.initAliyunCaptcha({
				SceneId: 'bv3tympas', // 场景ID。根据步骤二新建验证场景后，您可以在验证码场景列表，获取该场景的场景ID
				prefix: '14sny91', // 身份标。开通阿里云验证码2.0后，您可以在控制台概览页面的实例基本信息卡片区域，获取身份标
				mode: 'popup', // 验证码模式。popup表示要集成的验证码模式为弹出式。无需修改
				element: '#captcha-element', // 页面上预留的渲染验证码的元素，与原代码中预留的页面元素保持一致。
				button: '#captcha-button', // 触发验证码弹窗的元素。button表示单击登录按钮后，触发captchaVerifyCallback函数。您可以根据实际使用的元素修改element的值
				captchaVerifyCallback: this.captchaVerifyCallback, // 业务请求(带验证码校验)回调函数，无需修改
				onBizResultCallback: this.onBizResultCallback, // 业务请求结果回调函数，无需修改
				getInstance: this.getInstance, // 绑定验证码实例函数，无需修改
				slideStyle: {
					width: 360,
					height: 40,
				}, // 滑块验证码样式，支持自定义宽度和高度，单位为px。其中，width最小值为320 px
				language: 'cn', // 验证码语言类型，支持简体中文（cn）、繁体中文（tw）、英文（en）
			});
		},
		beforeUnmount() {
			this.captchaButton = null;

			// 必须删除相关元素，否则再次mount多次调用 initAliyunCaptcha 会导致多次回调 captchaVerifyCallback
			document.getElementById('aliyunCaptcha-mask')?.remove();
			document.getElementById('aliyunCaptcha-window-popup')?.remove();
		},
		methods: {
			openLoginBox() {
				this.openLogin = true;
				this.openPhone = false;
				this.isWechatBrowser = false;
			},
			checkPhone() {
				// 限制手机号长度不超过11位
				if (this.formData.phone && this.formData.phone.length > 11) {
					this.formData.phone = this.formData.phone.substring(0, 11);
				}

				if (this.isMobile(this.formData.phone)) {
					this.isPhone = false;
				} else {
					this.isPhone = true;
				}
			},

			checkPhone2() {
				// 限制手机号长度不超过11位
				if (this.registerData.phone && this.registerData.phone.length > 11) {
					this.registerData.phone = this.registerData.phone.substring(0, 11);
				}

				if (this.isMobile(this.registerData.phone)) {
					this.isPhone2 = false;
				} else {
					this.isPhone2 = true;
				}
			},

			// 切换到账号密码登录
			toLogin() {
				this.openLogin = true;
				this.openRegister = false;
				this.openPhone = false;
			},

			// 切换到注册
			toRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				})
			},

			// 切换到手机验证码登录
			toPhoneLogin() {
				this.openPhone = true;
				this.openLogin = false;
				this.openRegister = false;
			},

			// 账号密码登录
			accountLogin() {
				if (!this.loginData.account || !this.loginData.password) {
					return uni.showToast({
						title: '账号和密码不能为空',
						duration: 1000,
						icon: 'none'
					});
				}

				this.login_loading = true;
				$H.post('/app_user_account_login', {
					account: this.loginData.account,
					password: this.loginData.password,
					agent_code: this.agent_code
				}).then((res) => {
					this.login_loading = false;
					if (res.code == 200) {
						uni.setStorageSync('UserInfo', res.data);
						uni.showToast({
							title: res.msg,
							icon: 'success'
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							});
						}, 1000);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				}).catch((error) => {
					this.login_loading = false;
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					});
				});
			},

			// 注册
			register() {
				if (!this.registerData.account || !this.registerData.phone || !this.registerData.code || !this.registerData
					.password || !this.registerData.password2) {
					return uni.showToast({
						title: '请填写完整信息',
						duration: 1000,
						icon: 'none'
					});
				}

				if (!this.isMobile(this.registerData.phone)) {
					return uni.showToast({
						title: '手机号码格式错误',
						duration: 1000,
						icon: 'none'
					});
				}

				if (this.registerData.password !== this.registerData.password2) {
					return uni.showToast({
						title: '两次密码输入不一致',
						duration: 1000,
						icon: 'none'
					});
				}

				this.login_loading = true;
				$H.post('/app_user_register', {
					account: this.registerData.account,
					phone: this.registerData.phone,
					code: this.registerData.code,
					password: this.registerData.password,
					agent_code: this.agent_code
				}).then((res) => {
					this.login_loading = false;
					if (res.code == 200) {
						uni.showToast({
							title: '注册成功，请登录',
							icon: 'success'
						});
						setTimeout(() => {
							this.toLogin();
						}, 1500);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				}).catch((error) => {
					this.login_loading = false;
					uni.showToast({
						title: '注册失败，请重试',
						icon: 'none'
					});
				});
			},

			oneKeyPhoneLogin() {
				this.openPhone = true;
				this.openLogin = false;
				this.isWechatBrowser = false;
			},
			getConfig() {
				$H.post('/app_user_get_config').then((res) => {
					// console.log(res)
					if (res.code == 200) {
						this.config = res.data

						// 如果不是微信浏览器或微信登录未开启，则显示手机验证码登录
						if (!this.isWechatBrowser || this.config?.paw_login_open == 1) {
							this.openPhone = false;
							this.openLogin = true;
						}

						// 如果不是微信浏览器或微信登录未开启，则显示手机验证码登录
						if (!this.isWechatBrowser && this.config?.paw_login_open == 0) {
							this.openPhone = true;
							this.openLogin = false;
						}

						// 如果是微信浏览器且微信登录开启，则显示微信登录按钮
						if (this.isWechatBrowser && this.config?.wx_login_open == 1) {
							this.openLogin = false;
							this.openPhone = false;
						}

						// 如果不是微信浏览器或微信登录未开启，则显示手机验证码登录
						if (this.isWechatBrowser && this.config?.wx_login_open == 0 && this.config
							?.paw_login_open == 0) {
							this.openPhone = true;
							this.openLogin = false;
							this.isWechatBrowser = false;
						}

						if (this.isWechatBrowser && this.config?.wx_login_open == 0 && this.config
							?.paw_login_open == 1) {
							this.openPhone = false;
							this.openLogin = true;
							this.isWechatBrowser = false;
						}

						if (this.is_login == 1) {
							this.openPhone = false;
							this.openLogin = true;
							this.isWechatBrowser = false;
						}

					}
				})
			},

			// 检测是否在微信浏览器中
			checkIsWechatBrowser() {
				const ua = navigator.userAgent.toLowerCase();
				return ua.includes('micromessenger');
			},
			// 微信登录
			wechatLogin() {
				if (this.config.app_weixing_url) {
					// 获取当前域名
					const backurl = encodeURIComponent(`${window.location.origin}` + '/#/pages/login/login');
					// 跳转到微信授权页面
					window.location.href = this.config.app_weixing_url + `/wx_go.php?action=get_code&backurl=${backurl}`;
				} else {
					uni.showToast({
						title: "未配置微信授权接口，请联系管理员",
						icon: 'error'
					});
				}


			},

			// 使用微信信息登录
			async loginWithWechat() {
				uni.showLoading({
					title: '登录中...'
				});
				try {
					this.wxData.agent_code = this.agent_code;
					const result = await $H.post('/app_user_weixin_login', this.wxData);
					uni.hideLoading();
					if (result.code == 200) {
						uni.setStorageSync('UserInfo', result.data);
						uni.showToast({
							title: result.msg,
							icon: 'success'
						});
						if (result.data.phone) {
							// 登录成功后跳转到首页
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/index'
								});
							}, 1000);
						} else {
							uni.reLaunch({
								url: '/pages/my/mobile'
							});
						}

					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					});
				}
			},

			async captchaVerifyCallback(captchaVerifyParam) {

				const result = await $H.post('/aliyunVerify', {
					captchaVerifyParam: captchaVerifyParam,
					phone: this.formData.phone,
				});

				if (result.code == 200 && result.data == "T001") {
					return {
						captchaResult: true,
						bizResult: true,
					}
				} else {
					return uni.showToast({
						title: result.msg,
						duration: 1000,
						icon: 'none'
					});
				}
			},
			// 验证通过后调用
			onBizResultCallback(bizResult) {
				if (bizResult) {
					this.getPhoneCode()
				}
			},
			// 弹出验证框，popupId为组件id，用于支持验证通过后继续触发业务逻辑
			popup(popupId) {
				this.popupId = popupId;
				this.captchaButton.click();
			},
			// 获取验证码
			getPhoneCode() {
				let TIME_COUNT = 60;
				if (!this.timer) {
					this.showCode = true
					this.count = TIME_COUNT;
					this.timer = setInterval(() => {
						if (this.count > 0 && this.count <= TIME_COUNT) {
							this.count--
						} else {
							this.showCode = false
							clearInterval(this.timer);
							this.timer = null;
						}
					}, 1000);
				}
			},

			getMessage() {
				if (!this.isMobile(this.formData.phone)) {
					return uni.showToast({
						title: '手机号码输入有误',
						duration: 1000,
						icon: 'none',
						position: 'top'
					});
				}
				uni.showLoading({
					mask: true
				})
				$H.post('/app_user_get_message', {
					phone: this.formData.phone,
					type: 'sign'
				}).then((res) => {
					uni.hideLoading()
					if (res.code == 200 && res.msg == '短信发送成功') {
						this.getPhoneCode()
						return uni.showToast({
							title: res.msg,
							duration: 3000,
							icon: 'none',
							position: 'top'
						});
					} else {
						return uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none',
							position: 'top'
						});
					}
				})
			},

			isMobile(mobile) {
				return /^1[3-9]\d{9}$/.test(mobile)
			},

			routerIndex() {
				uni.reLaunch({
					url: '/pages/index/index'
				});
			},

			toIm() {
				uni.reLaunch({
					url: '/pages/im/imdetails'
				});
			},

			// 手机验证码登录
			phoneLogin() {

				for (let i in this.formData) {
					if (!this.formData[i]) {
						return uni.showToast({
							title: '手机号或验证码不能为空',
							duration: 1000,
							icon: 'none'
						});

					}
				}
				// console.log({
				//   type: 'login',
				//   phone: this.formData.phone,
				//   code: this.formData.code,
				//   agent_code: this.agent_code
				//   // password: this.password,
				//   // imgcode: this.imgcode
				// });
				this.login_loading = true;
				if (this.isMobile(this.formData.phone)) {
					$H.post('/app_user_phone_login', {
						type: 'login',
						phone: this.formData.phone,
						code: this.formData.code,
						agent_code: this.agent_code
						// password: this.password,
						// imgcode: this.imgcode
					}).then((res) => {
						if (res.code == 200) {

							this.show = true
							this.UserInfo = res.data
							// console.log(res.data,'data')
							uni.setStorageSync('UserInfo', res.data)

							uni.showToast({
								title: res.msg,
								duration: 1000,
								icon: 'none'
							});
							return uni.reLaunch({
								url: '/pages/index/index'
							});

						} else {
							this.login_loading = false;
							// this.tabCode()
							return uni.showToast({
								title: res.msg,
								duration: 1000,
								icon: 'none'
							});
						}
					})
				} else {
					this.login_loading = false;
					return uni.showToast({
						title: '手机号码有误',
						duration: 1000,
						icon: 'none'
					});
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	body {
		color: #535d76;
		background-color: #f0f3ff;
		font-size: 3.46667vw;
	}

	.child-view {
		transition: all .35s;
		width: 100%;
		height: 100%;
		position: relative;
		background-color: #f0f3ff;

		.title {
			.w-wz-conts {
				color: #323233 !important;
			}

		}

		.content-box {
			height: calc(100% - 26.93333vw);
			position: fixed;
			top: 12.8vw;
			left: 0px;
			right: 0px;
			bottom: 14.13333vw;
			overflow-x: hidden;
			overflow-y: auto;
			z-index: 1;
			padding-bottom: 3.2vw;

			.login {
				.van-cell-group {
					background: none !important;

					.van-field {
						line-height: 8vw;
					}

					.van-field__body {
						flex: 1;
					}

					.van-cell__value {
						align-items: center;
					}

					.van-cell {
						background: none !important;
					}

					.van-field__button {
						flex-shrink: 0;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}

				.van-cell-group--inset {
					margin: 0 4.26667vw;
					border-radius: 2.13333vw;
					overflow: hidden;
				}
			}
		}
	}

	.van-button--info {
		background-color: #3a9bf4 !important;
		border-color: #3a9bf4 !important;
	}

	.van-button--warnings {
		background-color: #07c160 !important;
		border-color: #07c160 !important;
	}

	.van-button__content .uni-icons {
		margin-right: 10px;
	}

	.index-bg {
		background-image: url('@/static/mine/login-bg.png');
	}

	.btn-radius {
		border-radius: 25px;
		color: #fff;
		margin-top: 50rpx;
		display: flex;
		justify-content: center;

		img {
			width: 60rpx;
		}

		span {
			flex: 1;
		}
	}

	.goRegister {
		font-size: 28rpx;
		color: #18b7fd;
		font-weight: 500;
	}
</style>